package main

import (
	"bytes"
	"flag"
	"fmt"
	"net"
	"net/http"
	"os"
	"strings"
	"time"
)

var server *string = flag.String("server", "122.195.54.10", "Use -server <serverip>")

func main() {
	flag.Parse()
	serverip := *server + ":6010"
	for {
		conn, err := net.Dial("tcp", serverip)
		if err != nil {
			panic(err)
		}
		data := time.Now().Format("2006-01-02 15:04:05") + " " + uploadExtIP()
		fmt.Print(data)
		conn.Write([]byte(data))
		time.Sleep(3 * time.Minute)
	}

}

func uploadExtIP() string {
	var realip string
	exip := get_external()
	inip := get_internal()
	realip = "Not ExternalIP,It is " + exip
	l := len(inip)
	for i := 0; i < l; i++ {
		if inip[i] == exip {
			realip = exip
		}
	}
	return realip + "\n"
}

func get_external() string {
	resp, err := http.Get("http://myexternalip.com/raw")
	if err != nil {
		os.Stderr.WriteString(err.Error())
		os.Stderr.WriteString("\n")
		os.Exit(1)
	}
	defer resp.Body.Close()
	buf := new(bytes.Buffer)
	buf.ReadFrom(resp.Body)
	return (strings.Replace(buf.String(), "\n", "", -1))
}

func get_internal() []string {
	var addr []string
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	for _, address := range addrs {
		// 检查ip地址判断是否回环地址
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				addr = append(addr, ipnet.IP.String())
			}
		}
	}
	return addr
}
